package jack.code.hnzb.task;

import com.google.gson.reflect.TypeToken;
import jack.code.hnzb.domain.model.DocumentModel;
import jack.code.hnzb.rule.SearchRule;
import jack.code.hnzb.service.SendMessage;
import jack.code.hnzb.utils.GsonUtil;
import jack.code.hnzb.utils.RedisUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

/**
 * 湖南招标监管网task
 * Created by LiJiakui on 17/8/30.
 */
@Component
public class BiddingTask {
    private static final Logger logger = Logger.getLogger(BiddingTask.class);
    //当前查询到的记录数
    private static final String REDIS_KEY = "hnzbjb-recordNum";
//    private static final String REDIS_LIST_KEY = "hnzbjb-list";
    private static final String WEB_URL = "http://www.bidding.hunan.gov.cn/jyxxzb/";


    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/1 * * * * ?")
    public void hnzbWatcher(){
        logger.info("----开始爬取数据-----");
        int sendTime = 0;//发送次数

        try {
            //如果当前任务已经发送了20次,那么就跳出任务,等待下一次
            while (sendTime<20){
                DocumentModel model = getDoc();
                if(model==null){
                    return ;
                }
                logger.info("\nresult---------"+model.getTitle()+"    "+model.getTime());
                //检索中环相关
                String rule = SearchRule.searchBidding(model.getBody());
                if(!"".equals(rule)){
                    sendTime++;
                    sendHnzb(model,rule);
                }
                RedisUtil.setJedisVal(REDIS_KEY,model.getId());
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            return ;
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            logger.info("本次检索结束");
        }

    }

    /**
     * 伪装浏览器代码
     * Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
     * @param
     * @return
     */

    private DocumentModel getDoc() throws Exception {
        int doneNum = 10;
        //查询最后一次任务的ID
        String recordNum = RedisUtil.getJedisVal(REDIS_KEY);
        if(StringUtils.isEmpty(recordNum)){
            recordNum = "1087";
        }
        Integer num = Integer.parseInt(recordNum);
        //需要查询的数据页数
        num = num+1;
        while (doneNum>0){
            //拼接查询链接地址
            String url=WEB_URL+num+".jhtml";
            //线程休眠2秒,防止被限制
            Thread.sleep(2000);
            Document doc = null;
            try {
                doc = Jsoup.connect(url).timeout(60000).get();
            } catch (HttpStatusException e) {
//                logger.info("没有查询到数据,当前尝试的地址为:"+url);
                num++;
                doneNum--;
                continue;
            }
            String sitemap = doc.getElementsByClass("sitemap").first().text();
            Element lbProclaimTitleEle = doc.getElementsByClass("div-title").first();
            Element lbReleasetTimeEle = doc.getElementsByClass("div-title2").first();
            Element bodyEle = doc.getElementsByClass("div-content").first();
            String lbProclaimTitle = lbProclaimTitleEle==null?"":lbProclaimTitleEle.text();
            String lbReleaseTime = lbReleasetTimeEle==null?"":lbReleasetTimeEle.text();
            String body = bodyEle==null?"":bodyEle.text();
            DocumentModel documentModel = new DocumentModel();
            documentModel.setBody(body);                //内容
            documentModel.setTitle(lbProclaimTitle);    //标题
            documentModel.setTime(lbReleaseTime);       //发布时间
            documentModel.setUrl(url);                  //查询地址
            documentModel.setId(String.valueOf(num));   //当前数据ID
            documentModel.setSitemap(sitemap);          //导航
            return documentModel;
        }
        return null;

    }

    private void sendHnzb(DocumentModel model,String rule) throws Exception{
        HttpResponse response = SendMessage.sendMsg1("信息来源:湖南招标监管网\n"+"命中索引:"+rule+"\n"+model.getTitle() + " \n" + model.getTime() + " \n" + "查询地址:" + model.getUrl());//钉钉机器人起飞
        if(response == null){
            return ;
        }else{
            if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                String result= EntityUtils.toString(response.getEntity());
                Map<String,String> resultMap = GsonUtil.fromJson(result,new TypeToken<HashMap<String,String>>(){}.getType());
                if(!"0".equals(resultMap.get("errcode"))){
                    SendMessage.sendMsg1("这条数据可能发送失败了,查询地址:"+model.getUrl());
                }
            }
        }
    }
//    @Scheduled(cron = "0 0 6 * * ?")
//    public void sayMorning(){
//        SendMessage.sendMsg1("一天之计在于晨,各位老大,小弟已经忙了一夜了,没有偷懒哦!");
//    }
//
//    @Scheduled(cron = "0 0 23 * * ?")
//    public void sayNight(){
//        SendMessage.sendMsg1("已经很晚了,老大您快睡觉吧,我自己可以的!");
//    }
}
